<?php
/**指定5.0.*版本安装tp5
 * composer create-project topthink/think=5.0.* tp5_test --prefer-dist
 * 因为5.1版里request()->module()，$request->controller()，$request->action()获取不到当前的模块，控制器，方法名
 */
namespace app\company\controller;

use app\company\model\Permissions;
use think\Controller;
use think\Request;

class Base extends Controller
{
    protected $com_id;
    protected $user_id;
    public function _initialize(){
        $request = Request::instance();
        define('MODULE_NAME', request()->module());
        define('CONTROLLER_NAME', $request->controller());
        define('ACTION_NAME', $request->action());
        //判断是否登入
        $userInfo = session("user_com");
        if(ACTION_NAME!='check_login' && ACTION_NAME!='login' && ACTION_NAME!='forget_pas'){
            if ($userInfo == null) {
                $this->redirect("User/login");
            }
            $this->com_id = $userInfo['com_id'];
            //--zj--begin
            $this->user_id = session("user_com")['id'];
            $this->assign('user_id', $this->user_id);
            //--zj--end
        }

        //是否是pjax
        $box_is_pjax = $this->request->isPjax();
        $this->assign('box_is_pjax', $box_is_pjax);

        //获取用户拥有权限的权限节点列表
        $hasPermissionsArr = [];
        if($userInfo["role_id"]) {
            $hasPermissionsArr = model("RolePermissionRelation")
                ->alias("rpr")
                ->join("com_permissions p","p.id=rpr.permission_id")
                ->where("rpr.role_id", $userInfo["role_id"])
                ->column("p.url","p.id");
        }
        session("hasPermissionsArr",$hasPermissionsArr);
        $this->assign("hasPermissionsArr",$hasPermissionsArr);

        //判断用户是否有正在运行的方法的权限
        if( !\app\company\logic\User::checkHasPermission(CONTROLLER_NAME."/".ACTION_NAME) ){
            echo "无权限";
            exit;
        }

        //全部的权限节点列表
        $treeMenu = $this->treeMenu();
        $this->assign('treeMenu', $treeMenu);

        //系统公告
        $this->sys_notices();
    }

    //系统公告 author:zj
    public function sys_notices()
    {
        $notices = db('sys_notice')->where('end_time', '>=', time())->order('create_time desc')->select();

        $eject = [];
        $notice_num = 0;
        foreach ($notices as &$row) {
            $userIds = explode(',', $row['user_ids']);
            if(!in_array($this->user_id, $userIds)){
                $notice_num++;
                $row['is_read'] = 0;        //未读
                if(!$eject){
                    $row['is_read'] = 1;        //未读
                    $eject = $row;
                    $this->sys_notcie_update($row['id'], $this->user_id);
                }
            }else{
                $row['is_read'] = 1;        //已读
            }
        }

        $notice_num = $notice_num > 0 ? $notice_num-1 : 0 ;

        $this->assign('notice_num', $notice_num);
        $this->assign('notices', $notices);
        $this->assign('eject', $eject);


    }

    //更新系统公告 author:zj
    public function sys_notcie_update($id = '', $userId = '')
    {
        $id = $id ? : input('id');
        $sys_notice = db('sys_notice')->find($id);

        $userId =  $userId ? : $this->user_id;
        if(!in_array($userId, explode(',', $sys_notice['user_ids'])) ){
            $user_ids = $sys_notice['user_ids'].','.$userId;
            db('sys_notice')->where('id', $id)->update(['user_ids'=>$user_ids]); 
        }

        if(request()->isAjax()){
            return $this->ajaxReturn(0,'','',$sys_notice);
        }

    }

    //获取左侧导航列表
    public function treeMenu(){
        // $treeMenu = cache('DB_TREE_MENU_'.UID);
        $treeMenu = Permissions::getTree();
        // cache('DB_TREE_MENU_'.UID, $treeMenu);
        return $treeMenu;
    }


    public function ajaxReturn($err=0, $msg='', $url='', $data = []){
        $result = [
            "err"   =>  $err,
            "msg"   =>  $this->getMsg($err, $msg),
            "url"   =>  $url,
            "data"  =>  $data,
        ];
        return json($result);
    }

    private function getMsg($err, $msg){
        if(!empty($msg)){
            return $msg;
        }else{
            $errList = [
                0   =>  "成功",
                1   =>  "请输入正确的验证码",
                2   =>  "请输入正确的账号",
                3   =>  "账号异常",
                4   =>  "请输入正确的密码",
            ];
            return isset($errList[$err]) ? $errList[$err] : '';
        }
    }

    /**
     * 企业后台部门列表下拉框选项
     */
    protected function company_department_select(){
        $department = db('com_department')->where('com_id', $this->com_id)->select();
        $department = toTree($department);
        $department = organization_tree($department);//部门列表
        $this->assign('department', $department);
    }

    /**
     * 页面js弹窗获取部门树列表 页面渲染
     * @return mixed
     */
    public function base_department_page(){
        $department = db('com_department')->where('com_id', $this->com_id)->field('id, pid, name')->select();
        foreach($department as $k=>$v){
            $department[$k]['title'] = $v['name'];
            unset($department[$k]['name']);
        }
        $department = toTree($department, 0, 'children');
        $department = json_encode($department);
        $this->assign('department', $department);
        return $department;
    }
    /**
     * 页面js弹窗获取部门树列表 ajax获取
     * @return mixed
     */
    public function base_department(){
        $department = db('com_department')->where('com_id', $this->com_id)->field('id, pid, name')->select();
        foreach($department as $k=>$v){
            $department[$k]['title'] = $v['name'];
            unset($department[$k]['name']);
        }
        $department = toTree($department, 0, 'children');
//        $department = json_encode($department);
        return json($department);
    }

    /**
     * 页面js弹窗获取部门下面人员
     * department_id        部门id
     * score                分值 获取初审人和终审人时传递
     * first_check_user_id  初审人id 或者 id数组
     * last_check_user_id   终审人id 或者 id数组
     * user_type            选择的用户类型 0无类型 1初审人 2终审人
     * user_name            搜索的用户名
     * is_child             是否包含子部门 暂时弃用
     * a_max                超标a分最大值 获取终审人需要
     * b_max                超标b分最大值 获取终审人需要
     */
    public function base_department_per(){
        $where = [];
        $param = input();
        $department_list = db('com_department')->where(['com_id'=>$this->com_id])->column('id, name');
        $department_id = input('department_id', 0, 'intval');//部门id
        $is_child = input('is_child', 1, 'intval');//是否包含子部门
        $score = input('score', 0, 'intval');//分值
        $first_check_user_id = isset($param['first_check_user_id']) ? $param['first_check_user_id'] : 0;//初审人id
        $last_check_user_id = isset($param['last_check_user_id']) ? $param['last_check_user_id'] : 0;//终审人id
        $user_type = input('user_type', 0, 'intval');//选择的用户类型
        $user_name = trim(input('user_name', '', 'addslashes'));//搜索的用户名
        $a_max = input('a_max', -1, 'intval');
        $b_max = input('b_max', -1, 'intval');
        //所有部门包括子级部门
        if(!$department_id && $is_child){
            $where['com_id'] = $this->com_id;
        //指定部门包括子级部门
        }elseif($department_id && $is_child){
            $ids = department_child([$department_id], $this->com_id);
            $where['department_id'] = ['in', $ids];
        }elseif($department_id){
            $where['department_id'] = $department_id;
        }
        $user_name && $where['name'] = ['like', '%'.$user_name.'%'];
        //删除管理员
        $where['role_id'] = ['neq',''];
        $where['type'] = 1;
        $user_list = db('users')->where($where)->field('id, name, job_number, department_id')->select();
        $userIds = array_column($user_list,'id');
        $users = db('com_prize_buckle_relation_users cu')
            ->join('com_prize_buckle cb', 'cu.prize_buckle_id = cb.id', 'left')
            ->where('cu.com_id', $this->com_id)
            ->where('cb.com_id', $this->com_id)
            ->where('cu.user_id', 'in', $userIds)
            ->column('cu.user_id, cb.integral_a, cb.integral_b');
        foreach($user_list as $k=>$v){
            if(isset($department_list[$v['department_id']])){
                $user_list[$k]['department_name'] = $department_list[$v['department_id']];
            }
            if(array_key_exists($v['id'], $users)){
                $user_list[$k]['limits']['a'] = $users[$v['id']]['integral_a'];       //奖扣分值范围
                $user_list[$k]['limits']['b'] = $users[$v['id']]['integral_b'];       //奖扣分值范围
            }
        }
        //获取终审人 返回去除初审人的数据
        if($user_type == 2){
            foreach($user_list as $k=>$v){
                //判断是否为多选
                if(is_array($first_check_user_id)){
                    $first_check_user_id = array_merge($first_check_user_id, [session("user_com.id")]);
                }else{
                    $first_check_user_id = [$first_check_user_id, session("user_com.id")];
                }
                //没有b分 在初审人里面
                if( !isset($v['limits']['b']) || $v['limits']['b']<$score || in_array($v['id'], $first_check_user_id) ){
                    unset($user_list[$k]);
                //超标事件终审人分值判断
//                }elseif( ($a_max>-1 && $b_max>-1) && $v['limits']['a']<$a_max && $v['limits']['b']<$b_max ){
                }elseif( ($a_max>-1 && $v['limits']['a']<$a_max) || ($b_max>-1 && $v['limits']['b']<$b_max) ){
                    unset($user_list[$k]);
                }
            }
        //获取初审人 返回去除终审人的数据
        }elseif($user_type == 1){
            foreach($user_list as $k=>$v){
                //判断是否为多选
                if(!is_array($last_check_user_id)){
                    $last_check_user_id = [$last_check_user_id];
                }
                if( !isset($v['limits']['b']) || in_array($v['id'], $last_check_user_id) ){
                    unset($user_list[$k]);
                }
            }
        }elseif($user_type == 0){
            foreach($user_list as $k=>$v){
                //判断是否为多选
                if(!is_array($last_check_user_id)){
                    $last_check_user_id = [$last_check_user_id];
                }
                if( in_array($v['id'], $last_check_user_id) ){
                    unset($user_list[$k]);
                }
            }
        }
        sort($user_list);
        $user_list = json_encode($user_list);
        return $user_list;
    }

    /**
     * 页面js弹窗搜索部门下面人员 暂弃用
     * department_id    部门id
     * search_name      搜索姓名
     */
    public function base_department_search(){
        $department_id = input('department_id', 0, 'intval');//部门id
        $search_name = input('search_name', '', 'addslashes');//人员姓名
        if(!trim($search_name)){
            return $this->ajaxReturn(1, '搜索有误');
        }
        $where = ['u.name'=>['like', '%'.$search_name.'%']];
        if(!$department_id){
            $where['u.com_id'] = $this->com_id;
        }else{
            $ids = department_child([$department_id], $this->com_id);
            $where['u.department_id'] = ['in', $ids];
        }
        $user_list = db('users')->alias('u')
            ->join('com_department d', 'd.id=u.department_id', 'LEFT')
            ->field('u.id, u.name, u.job_number, d.name as d_name')
            ->where($where)
            ->select();
        $userIds = array_column($user_list,'id');
        $users = db('com_prize_buckle_relation_users cu')
            ->join('com_prize_buckle cb', 'cu.prize_buckle_id = cb.id', 'left')
            ->where('cu.com_id', $this->com_id)
            ->where('cb.com_id', $this->com_id)
            ->where('cu.user_id', 'in', $userIds)
            ->column('cu.user_id, cb.integral_a, cb.integral_b');
        foreach($user_list as $k=>$v){
            if(array_key_exists($v['id'], $users)){
                $user_list[$k]['limits']['a'] = $users[$v['id']]['integral_a'];       //奖扣分值范围
                $user_list[$k]['limits']['b'] = $users[$v['id']]['integral_b'];       //奖扣分值范围
            }
        }
        $user_list = json_encode($user_list);
        return $user_list;
    }

    /**
     * 页面js弹窗获取事件分类列表
     */
    public function base_event_cate(){
        $eventLists = M('com_event_cate')
            ->where('com_id', 'in', [0,$this->com_id])
            ->where('is_del',0)
            ->field('id,pid,name')
            ->select();
        $eventList = toTree($eventLists, 0, 'children');
        $eventList = json_encode($eventList);
        $this->assign('eventList', $eventList);
        return json($eventList);
    }
    //事件编辑获取上级分类列表
    public function event_pid_list(){
        $list_user = M('com_event_cate')->where('pid', 0)->where('is_del',0)->field('id,pid,name')->select();
        $list_user_a = M('com_event_cate a')
            ->join('com_event_cate b','b.pid = a.id','left')
            ->where('a.pid = 0 and b.com_id = '.$this->com_id)
            ->where('b.is_del',0)
            ->field('b.id,b.pid,b.name')
            ->select();
        $list_user = array_merge($list_user,$list_user_a);
        $eventList = toTree($list_user, 0, 'children');
        $eventList = json_encode($eventList);
        $this->assign('eventList', $eventList);
        return json($eventList);
    }

    /**
     * 页面js弹窗获取事件分类下的列表
     * id           事件id  默认搜索所有
     * search_name  搜索的事件标题
     * is_check     是否是专审事件  0不是  1是
     */
    public function base_event_child(){
        $id = input('id', 0, 'intval');
        $search_name = input('search_name', '', 'addslashes');//事件标题
        $is_check = input('is_check', 0, 'intval');
        $parment = input();
        if(!$id){
            $ids = db('com_event_cate')->where(['com_id'=>$this->com_id])->whereOr(['com_id'=>0])->column('id');
        }else{
            $tmpIds = [$id];
            $ids = [];
            while (true) {
                $tmpIds = db('com_event_cate')->where(['pid'=>['in', $tmpIds], 'com_id'=>$this->com_id])->column('id');
                while (true) {
                    $tmpIds1 = db('com_event_cate')->where(['pid'=>['in', $tmpIds], 'com_id'=>$this->com_id])->column('id');
                    $ids = array_merge($ids, $tmpIds1, [intval($id)]);
                    if(!$tmpIds1) $ids = array_merge($ids, [$id]); break;
                }
                $ids = array_merge($ids, $tmpIds, [intval($id)]);
                if(!$tmpIds) $ids = array_merge($ids, [$id]); break;
            }
        }
        $where = ['a.cate_id'=>['in', $ids], 'a.com_id'=>$this->com_id,'a.is_del'=>0];
        if(isset($parment['is_check'])){
            $where['a.is_check'] = $is_check;
        }
        trim($search_name) && $where['a.name'] = ['like', '%'.trim($search_name).'%'];
        $event_child_info = db('com_event a')
            ->join('com_event_cate b', 'a.cate_id = b.id', 'LEFT')
            ->join('com_event_cate c', 'b.pid = c.id', 'LEFT')
            ->join('com_event_cate d', 'c.pid = d.id', 'LEFT')
            ->where($where)
            ->field('a.*,b.name cate_name,c.name p_cate_name, d.name pp_cate_name')
            ->select();

        foreach ($event_child_info as &$v) {
            $v['show_cate_name'] = trim($v['pp_cate_name'].$v['p_cate_name'].'/'.$v['cate_name'], '/');
        }
        if($is_check){
            foreach ($event_child_info as &$v) {
                $v['fuser'] = db('users a')->where('id', 'in', $v['first_check_user_id'])->column('id,name');
                $v['luser'] = db('users a')->where('id', 'in', $v['last_check_user_id'])->column('id,name');
            }
        }
        return json($event_child_info);
    }

    /**
     * 固定积分分类树
     */
    public function base_integral_cate(){
        $list = db('com_fixed_integral_cate')->where(['com_id'=>$this->com_id])->field('id, pid, name, type')->select();
        $list = toTree($list, 0, 'children');
        return json($list);
    }

    /**
     * 事件移动到指定事件分类下
     * cate_id      事件分类id
     * event_id     事件id
     */
    public function base_event_change(){
        $cate_id = input('cate_id', 0, 'intval');
        $event_id = input('event_id', 0, 'intval');
        $event_cate_exists = db('com_event_cate')->where('id', $cate_id)->find();
        $event_exists = db('com_event')->where('id', $event_id)->find();
        if(!$event_cate_exists || !$event_exists){
            return json(['err'=>1]);
        }
        db('com_event')->where('id', $event_id)->update(['cate_id'=>$cate_id]);
        return json(['err'=>0]);
    }
    //获取默认审核人
    public function get_check_people(){
        $uid = $this->user_id;
        $department = M('com_department a')
            ->join('users b','b.department_id=a.id','left')
            ->join('users c','c.id=a.first_check_user_id','left')
            ->join('users d','d.id=a.last_check_user_id','left')
            ->where('b.id',$uid)
            ->field('a.first_check_user_id,a.last_check_user_id,c.name first_name,d.name last_name')
            ->find();
        $this->assign('check_user_data',$department);
    }

}
